import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:flutter_demo/api/shop_api.dart';
import 'package:flutter_demo/entity/base_response.dart';
import 'package:flutter_demo/entity/shop.dart';
import 'package:flutter_demo/page/base_page_state.dart';
import 'package:flutter_demo/page/mall/shop_detail_goods_widget.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';

class ShopDetailPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ShopDetailPageState();
  }
}

class ShopDetailPageState extends BasePageState<ShopDetailPage>
    with SingleTickerProviderStateMixin {
  ShopApi _shopApi = ShopApi();
  Shop _shop;
  TabController _tabController;
  final double _top =
      MediaQueryData.fromWindow(window).padding.top + kToolbarHeight;
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    appBarController.visible = false;
    _tabController = TabController(
      length: 3,
      vsync: this,
    );
    _fetchData();
  }

  @override
  Widget buildBody(BuildContext context) {
    if (_shop == null) {
      return Container(
        height: 400,
      );
    } else {
      return NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              pinned: true,
              expandedHeight: _top + 115,
              elevation: 0,
              title: Text('详情'),
              flexibleSpace: FlexibleSpaceBar(
                background: _buildShopHeader(_shop.seller),
                centerTitle: true,
                collapseMode: CollapseMode.pin,
              ),
              bottom: PreferredSize(
                preferredSize: Size.fromHeight(36),
                child: TabBar(
                  controller: _tabController,
                  indicatorSize: TabBarIndicatorSize.label,
                  indicatorWeight: 3,
                  tabs: <Widget>[
                    Tab(text: '商品'),
                    Tab(text: '评论'),
                    Tab(text: '商家')
                  ],
                ),
              ),
            ),
          ];
        },
//        innerScrollPositionKeyBuilder: () {
//          return _top + 115;
//        },
        pinnedHeaderSliverHeightBuilder: () {
          return _top;
        },
        body: _buildShopContent(),
      );
    }
  }

  _fetchData() async {
    BaseResponse response = await _shopApi.getShopDetail();
    setState(() {
      _shop = Shop.fromJson(response.data);
    });
  }

  _buildShopHeader(Seller seller) {
    return Container(
      child: Stack(children: <Widget>[
        CachedNetworkImage(
          imageUrl: seller.avatar,
          width: double.infinity,
          height: double.infinity,
          fit: BoxFit.cover,
        ),
        BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 15, sigmaY: 15),
          child: new Container(
            color: Colors.black.withOpacity(0.4),
          ),
        ),
        Column(
          children: <Widget>[
            Padding(
              padding:
                  EdgeInsets.only(left: 25, right: 25, top: _top, bottom: 15),
              child: Row(
                children: <Widget>[
                  CachedNetworkImage(
                    imageUrl: seller.avatar,
                    width: 64,
                    height: 64,
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Image.asset(
                              'res/images/brand.png',
                              width: 30,
                              height: 18,
                            ),
                            Padding(
                                padding: EdgeInsets.only(left: 5),
                                child: Text(
                                  seller.name,
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 18),
                                ))
                          ],
                        ),
                        Text(
                          '${seller.description} ${seller.deliveryTime}分钟内送达',
                          style: TextStyle(color: Colors.white, fontSize: 14),
                        ),
                        Row(
                          children: <Widget>[
                            Image.asset(
                              'res/images/decrease.png',
                              width: 12,
                              height: 12,
                            ),
                            Padding(
                                padding: EdgeInsets.only(left: 5),
                                child: Text(
                                  '在线支付满${seller.minPrice}减${seller.deliveryPrice}',
                                  style: TextStyle(
                                      color: Colors.white, fontSize: 14),
                                ))
                          ],
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              color: Color.fromARGB(50, 7, 17, 27),
              child: Padding(
                padding:
                    const EdgeInsets.symmetric(vertical: 5, horizontal: 10),
                child: Row(
                  children: <Widget>[
                    Image.asset(
                      'res/images/bulletin.png',
                      width: 21,
                      height: 12,
                    ),
                    Expanded(
                      child: Padding(
                        padding: EdgeInsets.only(left: 5, right: 5),
                        child: Text(
                          seller.bulletin,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(color: Colors.white, fontSize: 12),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            )
          ],
        ),
      ]),
    );
  }

  _buildShopContent() {
    return Container(
      child: TabBarView(
        controller: _tabController,
        children: <Widget>[
          ShopDetailGoodsWidget(shop: _shop),
          _buildCommentContent(),
          _buildShopInfoView()
        ],
      ),
    );
  }

  Widget _buildShopInfoView() {
    return SingleChildScrollView(
      child: Container(
        child: Column(
          children: <Widget>[
            Container(
              padding: EdgeInsets.all(15),
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: <Widget>[
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            _shop.seller.name,
                            style: TextStyle(fontSize: 16),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(top: 5),
                            child: Row(
                              children: <Widget>[
                                RatingBar(
                                  initialRating: _shop.seller.foodScore,
                                  allowHalfRating: true,
                                  itemCount: 5,
                                  itemSize: 24,
                                  itemPadding:
                                      EdgeInsets.symmetric(horizontal: 0),
                                  itemBuilder: (context, _) => Icon(
                                    Icons.star,
                                    color: Colors.amber,
                                  ),
                                ),
                                Text(
                                    '${_shop.seller.foodScore}分（${_shop.ratings.length}）月售${_shop.seller.sellCount}单')
                              ],
                            ),
                          )
                        ],
                      ),
                      Expanded(
                        child: Container(),
                      ),
                      Icon(
                        Icons.favorite,
                        color: Colors.red,
                      )
                    ],
                  ),
                  Divider(),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text('起送价'),
                      ),
                      Expanded(
                        child: Text('商家配送价'),
                      ),
                      Expanded(
                        child: Text('平均配送时间'),
                      )
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Text('${_shop.seller.minPrice}'),
                      ),
                      Expanded(
                        child: Text('${_shop.seller.deliveryPrice}'),
                      ),
                      Expanded(
                        child: Text('${_shop.seller.deliveryTime}'),
                      )
                    ],
                  )
                ],
              ),
            ),
            Divider(
              height: 15,
              thickness: 15,
              color: Colors.black12,
            ),
            Container(
              padding: EdgeInsets.all(15),
              color: Colors.white,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(
                    '公共与活动',
                    style: TextStyle(fontSize: 16),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(
                        left: 5, right: 5, top: 5, bottom: 15),
                    child: Text(
                      '${_shop.seller.bulletin}',
                      style: TextStyle(color: Colors.redAccent),
                    ),
                  ),
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: _buildSupportsView(),
                  )
                ],
              ),
            ),
            Divider(
              height: 15,
              thickness: 15,
              color: Colors.black12,
            ),
            Container(
              color: Colors.white,
              padding: EdgeInsets.all(15),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Padding(
                    padding: const EdgeInsets.only(bottom: 8.0),
                    child: Text(
                      '商家实景',
                      style: TextStyle(fontSize: 16),
                    ),
                  ),
                  Column(
                    children: _buildShopImagesView(),
                  )
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  // 构建支持信息列表
  List<Widget> _buildSupportsView() {
    List<Widget> widgets = [];
    _shop.seller.supports.forEach((support) {
      widgets.add(Row(
        children: <Widget>[
          Image.asset(
            'res/images/decrease.png',
            width: 16,
            height: 16,
          ),
          Text('${support.description}')
        ],
      ));
      widgets.add(Divider());
    });
    return widgets;
  }

  // 构建商户图片列表
  List<Widget> _buildShopImagesView() {
    List<Widget> widgets = [];
    _shop.seller.pics.forEach((pic) {
      widgets.add(CachedNetworkImage(
        imageUrl: pic,
      ));
    });
    return widgets;
  }

  // 构建评论信息
  Widget _buildCommentContent() {
    return ListView.separated(
        itemBuilder: (BuildContext context, int index) {
          if (index == 0) {
            return _buildCommentHeader();
          } else {
            return _buildCommentItem(context, index);
          }
        },
        separatorBuilder: (BuildContext context, int index) {
          return Divider(
            height: 0.5,
            thickness: 0.5,
          );
        },
        itemCount: _shop.ratings.length + 1);
  }

  Widget _buildCommentHeader() {
    return Container(
      padding: EdgeInsets.all(15),
      child: Row(
        children: <Widget>[
          Column(
            children: <Widget>[
              Text(
                '${_shop.seller.score}',
                style: TextStyle(color: Colors.redAccent, fontSize: 20),
              ),
              Text('综合得分'),
              Text('高于${_shop.seller.rankRate}%的周边商家')
            ],
          ),
          VerticalDivider(),
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Row(
                children: <Widget>[
                  Text('商品评分'),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: RatingBar(
                        initialRating: _shop.seller.foodScore,
                        allowHalfRating: true,
                        itemCount: 5,
                        itemSize: 24,
                        itemPadding: EdgeInsets.symmetric(horizontal: 0),
                        itemBuilder: (context, _) => Icon(
                              Icons.star,
                              color: Colors.amber,
                            )),
                  ),
                  Text(
                    '${_shop.seller.foodScore}',
                    style: TextStyle(color: Colors.amber),
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Text('服务态度'),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 5),
                    child: RatingBar(
                        initialRating: _shop.seller.serviceScore,
                        allowHalfRating: true,
                        itemCount: 5,
                        itemSize: 24,
                        itemPadding: EdgeInsets.symmetric(horizontal: 0),
                        itemBuilder: (context, _) => Icon(
                              Icons.star,
                              color: Colors.amber,
                            )),
                  ),
                  Text(
                    '${_shop.seller.serviceScore}',
                    style: TextStyle(color: Colors.amber),
                  )
                ],
              ),
              Row(
                children: <Widget>[
                  Text('送达时间'),
                  Text('${_shop.seller.deliveryTime}分钟')
                ],
              )
            ],
          )
        ],
      ),
    );
  }

  Widget _buildCommentItem(BuildContext context, int index) {
    var comment = _shop.ratings[index - 1];
    return Container(
      padding: EdgeInsets.all(15),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 8),
            child: CircleAvatar(
              radius: 16,
              backgroundImage: CachedNetworkImageProvider('${comment.avatar}'),
            ),
          ),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Row(
                  children: <Widget>[
                    Expanded(child: Text('${comment.username}')),
                    Text('${comment.rateTime}')
                  ],
                ),
                Row(
                  children: <Widget>[
                    RatingBar(
                        initialRating: comment.score.toDouble(),
                        allowHalfRating: true,
                        itemCount: 5,
                        itemSize: 12,
                        itemPadding: EdgeInsets.symmetric(horizontal: 0),
                        itemBuilder: (context, _) => Icon(
                              Icons.star,
                              color: Colors.amber,
                            )),
                    comment.deliveryTime == 0
                        ? Container()
                        : Text('${comment.deliveryTime}分钟送达')
                  ],
                ),
                Text('${comment.text}'),
                Wrap(
                  children: _buildRecommendsView(comment),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  List<Widget> _buildRecommendsView(Ratings comment) {
    List<Widget> widgets = [];
    if (comment.recommend != null) {
      comment.recommend.forEach((recommend) {
        widgets.add(Padding(
          padding: const EdgeInsets.all(3),
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 3, horizontal: 5),
            decoration: BoxDecoration(
                color: Color.fromARGB(255, 245, 245, 245),
                border: Border.all(width: 0.5, color: Colors.black12),
                borderRadius: BorderRadius.all(Radius.circular(3))),
            child: Text('$recommend'),
          ),
        ));
      });
    }
    return widgets;
  }
}
